package com.tgjorgoski.utils;

import java.awt.Component;
import java.awt.datatransfer.Clipboard;

import javax.swing.JLabel;

public class ClipboardUtil {

	/**
	 * Key used in app context to lookup Clipboard to use if access to
	 * System clipboard is denied.
	 */
	private static Object SandboxClipboardKey = new Object();

	private static Component dummy = new JLabel();
	
	/**
	 * Returns the clipboard to use for cut/copy/paste.
	 * 
	 */
	public static Clipboard getDefaultClipboard() {
		if (canAccessSystemClipboard()) {
			return dummy.getToolkit().getSystemClipboard();
		}
		Clipboard clipboard = (Clipboard)sun.awt.AppContext.getAppContext().
											 get(SandboxClipboardKey);
		if (clipboard == null) {
			clipboard = new Clipboard("Sandboxed SDoc Component Clipboard");
			sun.awt.AppContext.getAppContext().put(SandboxClipboardKey,
												   clipboard);
		}
		return clipboard;
	}
	/**
	 * Returns true if it is safe to access the system Clipboard.
	 */
	private static boolean canAccessSystemClipboard() {
		SecurityManager sm = System.getSecurityManager();
		if (sm != null) {
			try {
				sm.checkSystemClipboardAccess();
				return true;
			} catch (SecurityException se) {
				return false;
			}
		}
		return true;
	}
		

}
